<template>
  <view class="countdown-container">
    <text v-if="showDays" class="time-unit">{{ formatTime(days) }}</text>
    <text v-if="showDays" class="time-separator">{{ separator }}</text>
    <text class="time-unit">{{ formatTime(hours) }}</text>
    <text class="time-separator">{{ separator }}</text>
    <text class="time-unit">{{ formatTime(minutes) }}</text>
    <text v-if="showSeconds" class="time-separator">{{ separator }}</text>
    <text v-if="showSeconds" class="time-unit">{{ formatTime(seconds) }}</text>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 定义 props
const props = defineProps({
  // 目标时间戳（毫秒）
  targetTime: {
    type: Number,
    required: true
  },
  // 是否显示天数
  showDays: {
    type: Boolean,
    default: true
  },
  // 是否显示秒数
  showSeconds: {
    type: Boolean,
    default: true
  },
  // 分隔符
  separator: {
    type: String,
    default: ':'
  },
  // 是否自动开始
  autoStart: {
    type: Boolean,
    default: true
  }
})

// 定义 emits
const emit = defineEmits(['finish'])

// 响应式数据
const days = ref(0)
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)
const timer = ref(null)

// 开始倒计时
const start = () => {
  calculateTime()
  timer.value = setInterval(() => {
    calculateTime()
  }, 1000)
}

// 停止倒计时
const stop = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

// 计算时间
const calculateTime = () => {
  const now = Date.now()
  const diff = props.targetTime - now
  
  if (diff <= 0) {
    stop()
    emit('finish')
    return
  }
  
  const secondsValue = Math.floor(diff / 1000)
  days.value = Math.floor(secondsValue / (24 * 60 * 60))
  hours.value = Math.floor((secondsValue % (24 * 60 * 60)) / (60 * 60))
  minutes.value = Math.floor((secondsValue % (60 * 60)) / 60)
  seconds.value = secondsValue % 60
}

// 格式化时间
const formatTime = (time) => {
  return time.toString().padStart(2, '0')
}

// 生命周期钩子
onMounted(() => {
  if (props.autoStart) {
    start()
  }
})

onUnmounted(() => {
  stop()
})
</script>

<style scoped>
.countdown-container {
  display: flex;
  align-items: center;
}

.time-unit {
  display: inline-block;
  padding: 10rpx 15rpx;
  background-color: #007aff;
  color: white;
  border-radius: 5rpx;
  font-size: 24rpx;
  font-family: monospace;
}

.time-separator {
  margin: 0 5rpx;
  color: #666;
  font-size: 24rpx;
}
</style>